package ext.tianma.workflow;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import wt.access.AccessControlHelper;
import wt.access.AccessPermission;
import wt.doc.WTDocument;
import wt.enterprise.Master;
import wt.enterprise.RevisionControlled;
import wt.epm.EPMDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectNoLongerExistsException;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleManaged;
import wt.lifecycle.State;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.team.Team;
import wt.team.TeamHelper;
import wt.team.TeamManaged;
import wt.team.TeamReference;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfBlock;
import wt.workflow.engine.WfConnector;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WorkItem;

import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.windchill.enterprise.wip.WIPUtils;

import ext.tianma.access.AccessUtil;

public class BomWorkFlowUtil {
	private static boolean VERBOSE = false;
    private static final String LEVE2MATERIAL = "TwoLevelMaterial";
    private static final String[] CURRENT_STATES_1 = { "INWORK" };
    private static final String[] CURRENT_STATES_2 = { "INWORK", "NewProduct", "MassProductionRelease", "APPROVAL" };
    private static final String WORKFLOW_SAMPLE_APPROVE = "样品承认及批准流程";
    private static final String DOCUMENTTYPE_2D = "DrawingDoc";
    //权限集合
    private static List< AccessPermission >  apList = new ArrayList<AccessPermission>();
    
    static{
    	//修改权限
    	apList.add(AccessPermission.MODIFY);
    	//读取权限
    	apList.add(AccessPermission.READ);
    }
    /**
     * 检查BOM通过条件
     * 
     * @param WTObject
     *            object
     * @return ArrayList<WTObject> reviewObjects
     * @throws WTException
     * @author valkyrie
     */
    
    public static ArrayList<WTObject> checkBomPassCondition(WTObject object) throws WTException {
	HashSet<WTObject> reviewObject = new HashSet<WTObject>();
	HashSet<WTPart> currentParts = new HashSet<WTPart>();
	HashSet<WTPart> reviewObject_part = new HashSet<WTPart>();
	ArrayList<WTObject> reviewObjects = new ArrayList<WTObject>();
	ArrayList<String> errorInfor_workflow = new ArrayList<String>();
	ArrayList<String> errorInfor_checkout = new ArrayList<String>();
	if (object instanceof WTPart) {
	    WTPart endPart = (WTPart) object;
	    ArrayList<WTPart> childrens = getAllPartChildrens(endPart);
	    currentParts.addAll(childrens);
	    for (WTPart part : currentParts) {
		// 假如当前部件类型不为二级原材料
		if (!isObjectType(part, LEVE2MATERIAL)) {
		    // 假如当前状态为正在工作
		    if (isCurrentState(part, CURRENT_STATES_1)) {
			// 将当前部件及其相关的图档及CAD加入reviewObject集合对象
			reviewObject.add(part);
			// 收集相关的ERP文档及图档
			reviewObject.addAll(collectionAssociatedObject(part));
			reviewObject_part.add(part);
		    }
		    // 假如当前状态不为正在工作，新建，发布和批准状态时
		    if (!isCurrentState(part, CURRENT_STATES_2)) {
			ArrayList<WfProcess> wfps = getAssociatedProcesse(part);
			for (WfProcess wfp : wfps) {
			    if (wfp.getState().equals(WfState.OPEN_RUNNING) && !WORKFLOW_SAMPLE_APPROVE.equals(wfp.getTemplate().getName())) {
				errorInfor_workflow.add(part.getNumber());
			    }
			    // 关联的流程状态不为正在运行状态
			    if (!wfp.getState().equals(WfState.OPEN_RUNNING)) {
				reviewObject.add(part);
				reviewObject_part.add(part);
			    }
			}
		    }
		}
	    }
	    for (WTPart part : reviewObject_part) {
		if (WIPUtils.isCheckOutValid(part, "full")) {
		    errorInfor_checkout.add(part.getNumber());
		}
	    }
	    if (!errorInfor_checkout.isEmpty()) {
		throw new WTException("检出错误");
	    }
	    if (!errorInfor_workflow.isEmpty()) {
		throw new WTException("关联部件流程不能为运行中");
	    }
	} else {
	    throw new WTException("Wasn't WTPart,Please check it!");
	}
	reviewObjects.addAll(reviewObject);
	return reviewObjects;
    }
    
    /**
     * 检查BOM下所有子件是否还有在走样品承认流程，有的话给出提示列表
     * 
     * @param WTObject
     *            object
     * @return ArrayList<WTPart>
     * @throws WTException
     * @author valkyrie
     */
    public static ArrayList<WTPart> getListOfRuningSampleApproveWF(WTObject object) throws WTException {
	ArrayList<WTPart> listparts = new ArrayList<WTPart>();
	HashSet<WTPart> currentParts = new HashSet<WTPart>();
	ArrayList<WTPart> subParts = new ArrayList<WTPart>();
	if (object instanceof WTPart) {
	    WTPart endPart = (WTPart) object;
	    subParts = getAllPartChildrens(endPart);
	    for (WTPart part : subParts) {
		ArrayList<WfProcess> wfps = getAssociatedProcesse(part);
		for (WfProcess wfp : wfps) {
		    if (wfp.getState().equals(WfState.OPEN_RUNNING) && WORKFLOW_SAMPLE_APPROVE.equals(wfp.getTemplate().getName())) {
			currentParts.add(part);
		    }
		}
	    }
	    listparts.addAll(currentParts);
	}
	return listparts;
    }
    
    /**
     * 随签对象列表中的所有对象生命周期状态设置为指定生命周期状态
     * 
     * @param pbo
     *            reviewObjects toState
     * @throws WTException
     * @author valkyrie
     */
    public static void setLifeCycleState(WTObject pbo, ArrayList<WTObject> reviewObjects, String toState) throws WTException {
	if (toState == null || toState.trim().length() <= 0) {
	    return;
	}
	if (pbo instanceof WTPart) {
	    WTPart endPart = (WTPart) pbo;
	    for (WTObject review : reviewObjects) {
		if (review instanceof LifeCycleManaged) {
		    LifeCycleManaged lcm = (LifeCycleManaged) review;
		    String currentlcmState = lcm.getLifeCycleState().toString();
		    if (!currentlcmState.equalsIgnoreCase(toState)) {
			LifeCycleHelper.service.setLifeCycleState(lcm, State.toState(toState));
		    }
		}
	    }
	    String endPartState = endPart.getLifeCycleState().toString();
	    if (!endPartState.equalsIgnoreCase(toState)) {
		LifeCycleHelper.service.setLifeCycleState(endPart, State.toState(toState));
	    }
	}
	
    }
    
    private static ArrayList<WTPart> getAllPartChildrens(WTPart parent) {
	ArrayList<WTPart> childeParts = new ArrayList<WTPart>();
	if (parent != null) {
	    try {
		QueryResult qr = WTPartHelper.service.getUsesWTPartMasters(parent);
		while (qr.hasMoreElements()) {
		    WTPartUsageLink link = (WTPartUsageLink) qr.nextElement();
		    WTPart child = (WTPart) getLatestObject((WTPartMaster) link.getUses());
		    childeParts.add(child);
		    childeParts.addAll(getAllPartChildrens(child));
		}
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
	return childeParts;
    }
    
    private static RevisionControlled getLatestObject(Master master) throws WTException {
	QueryResult queryResult = VersionControlHelper.service.allVersionsOf(master);
	return (RevisionControlled) queryResult.nextElement();
    }
    
    private static boolean isObjectType(WTObject object, String objectType) throws WTException {
	if (objectType.equals("") || objectType == null || object == null)
	    return false;
	TypeIdentifier typeidentifier = ClientTypedUtility.getTypeIdentifier(object);
	String typeName = typeidentifier.getTypename();
	if (typeName.indexOf(objectType) >= 0) {
	    return true;
	}
	return false;
    }
    
    private static boolean isCurrentState(LifeCycleManaged lcm, String[] states) {
	boolean isCurrentState = false;
	String currentState = lcm.getState().toString();
	for (String state : states) {
	    if (state.equals(currentState)) {
		isCurrentState = true;
	    }
	}
	return isCurrentState;
    }
    
    private static ArrayList<WfProcess> getAssociatedProcesse(WTObject object) throws WTException {
	ArrayList<WfProcess> wfprocesses = new ArrayList<WfProcess>();
	QueryResult qrprocesser = getAssociatedProcesses(object);
	while (qrprocesser.hasMoreElements()) {
	    Object objectprocessor = qrprocesser.nextElement();
	    wfprocesses.add((WfProcess) objectprocessor);
	}
	return wfprocesses;
    }
    
    private static QueryResult getAssociatedProcesses(WTObject object) throws WTException {
	QueryResult qr = null;
	ReferenceFactory referencefactory = new ReferenceFactory();
	String ref = referencefactory.getReferenceString(object);
	QuerySpec queryspec = new QuerySpec(WfProcess.class);
	SearchCondition sc = new SearchCondition(WfProcess.class, "businessObjReference", "=", ref);
	queryspec.appendSearchCondition(sc);
	qr = PersistenceHelper.manager.find(queryspec);
	return qr;
    }
    
    private static HashSet<WTDocument> getReferencrDoc(final String docType, final WTPart wtPartSon) throws WTException {
	HashSet<WTDocument> wtDocs = new HashSet<WTDocument>();
	for (QueryResult qr1 = WTPartHelper.service.getReferencesWTDocumentMasters(wtPartSon); qr1.hasMoreElements();) {
	    WTObject objdoc = (WTObject) qr1.nextElement();
	    if (objdoc instanceof WTDocument) {
		String curType = wt.type.TypedUtility.getExternalTypeIdentifier((wt.type.Typed) objdoc);
		curType = curType.trim();
		String shortCurType = curType.substring(curType.lastIndexOf(".") + 1, curType.length());
		if (shortCurType.equals(docType)) {
		    WTDocument wtdoc = (WTDocument) objdoc;
		    wtDocs.add(wtdoc);
		}
	    }
	}
	return wtDocs;
    }
    
    private static ArrayList<WTObject> collectionAssociatedObject(WTPart part) throws WTException {
	ArrayList<WTObject> associatedObject = new ArrayList<WTObject>();
	QueryResult qr = ext.com.core.CoreUtil.getAssociatedCADDocuments(part);
	while (qr.hasMoreElements()) {
	    Object object = qr.nextElement();
	    if (object instanceof EPMDocument) {
		associatedObject.add((EPMDocument) object);
	    }
	}
	associatedObject.addAll(getReferencrDoc(DOCUMENTTYPE_2D, part));
	return associatedObject;
    }
    
    
    /**
     * add by kwang 2013-11-20  添加一个参与者到流程的某一指定角色中
     * @param processObj  selt
     * @param rolename	角色
     * @param wtObject 	PBO
     */
    public static void replacePrincipalToProcessRole(Object processObj,String rolename,WTObject wtObject){
    	System.out.println( "Debug   开始运行替换角色..." );
    	if( processObj == null || rolename == null || wtObject == null ){
    		System.out.println( "Debug   参数列表异常!" );
    		return ;
    	}
    	
    	try {
			WTPrincipal principal = getPrincipal(wtObject);
			if( principal != null ){
				System.out.println( "Debug   addPrincipalToProcessRole..." );
				addPrincipalToProcessRole(processObj,rolename,principal);
				System.out.println( "Debug   替换角色成功!" );
			}	
			System.out.println( "Debug   replacePrincipalToProcessRole..." );
		} catch (WTException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 获取对象的创建者
     */
	public static WTPrincipal getPrincipal( WTObject wtObject ) throws WTException{
		
		WTPrincipal principal = SessionHelper.manager.getPrincipal();	
		if( principal == null && wtObject != null ){
			
			if( wtObject instanceof WTPart ){
				WTPart part = (WTPart)wtObject;
				//获取PBO的创建者
				WTPrincipalReference pReference = part.getCreator();
				if( pReference != null ){
					principal = pReference.getPrincipal();
					System.out.println( "Debug   WTPrincipalReference："+principal.getName() );	
				}									
			}
		}
		System.out.println( "Debug   principal:"+principal.getName() );
		return principal;
	}

	/**
	 * 添加一个参与者到流程的某一指定角色中
	 * 
	 * @param processObj
	 *            工作流本身
	 * @param rolename
	 *            指定角色
	 * @param prin
	 *            被添加的承担者（用户或用户组）
	 * @return 若添加成功，返回true；否则返回false <br>
	 */
	public static boolean addPrincipalToProcessRole(Object processObj,String rolename ) {
		boolean flag = true;
		
		// 获得对象的相关进程
		WfProcess process = getProcess(processObj);
		
		if (process == null){
			return false;
		}
		System.out.println( "Debug   pricess："+process.getName() );
		try {			
			Team team = getTeam(process);
			
			Role role = Role.toRole(rolename) ;
			
			WTPrincipalReference newPrincipalRef = process.getCreator() ;
			
			if( newPrincipalRef != null ){
				WTPrincipal newPrincipal = newPrincipalRef.getPrincipal() ;
				
				//清除流程参与者
				System.out.println( "Debug   清除流程参与者..." );
				clearProcessRole( processObj , rolename ) ; 
				
				//添加流程参与者
				System.out.println( "Debug   更换流程参与者..." );
				System.out.println( "Debug   更换的角色: "+role.getFullDisplay() );
				System.out.println( "Debug   新的承担者:"+ newPrincipal.getName() );
				team.addPrincipal(role, newPrincipal);
			}
			
			
		} catch (Exception e) {
			if (VERBOSE) {
				System.out.println("WorkflowUtil.addPrincipalToProcessRole : error");
				e.printStackTrace();
			}
			
			flag = false;
		} finally {
			
		}
		
		return flag;
	}
	
	/**
	 * 添加一个参与者到流程的某一指定角色中
	 * 
	 * @param processObj
	 *            工作流本身
	 * @param rolename
	 *            指定角色
	 * @param prin
	 *            被添加的承担者（用户或用户组）
	 * @return 若添加成功，返回true；否则返回false <br>
	 */
	public static boolean addPrincipalToProcessRole(Object processObj,String rolename, WTPrincipal prin) {
		boolean flag = true;
		
		// 获得对象的相关进程
		WfProcess process = getProcess(processObj);
		
		if (process == null){
			return false;
		}
		System.out.println( "Debug   pricess："+process.getName() );
		try {
			Team team = getTeam(process);
			System.out.println( "Debug   team："+team.getName() );
			Enumeration enum1 = getRoleEnumeration(team, rolename);
			
			while (enum1 != null && enum1.hasMoreElements()) {
				WTPrincipal wtp = ((WTPrincipalReference) enum1.nextElement()).getPrincipal();
				
				if (wtp.equals(prin)){
					System.out.println( "Debug   获取团队成员:"+wtp.getName() );
					return false;
				}
				
			}

			Role role = Role.toRole(rolename) ;
			
			//清除流程参与者
			System.out.println( "Debug   清除流程参与者..." );
			clearProcessRole( processObj , rolename ) ; 
			
			//添加流程参与者
			System.out.println( "Debug   添加流程参与者..." );
			System.out.println( "Debug   添加者role:"+role.getFullDisplay() );
			System.out.println( "Debug   被添加的承担着:"+prin.getName() );
			team.addPrincipal(role, prin);
		} catch (Exception e) {
			if (VERBOSE) {
				System.out.println("WorkflowUtil.addPrincipalToProcessRole : error");
				e.printStackTrace();
			}
			
			flag = false;
		} finally {
			
		}
		
		return flag;
	}

	/**
	 * 清空流程团队中指定角色的参与者
	 * 
	 * @param processObj
	 *            工作流本身
	 * @param rolename
	 *            指定角色
	 * @throws WTException
	 */
	public static void clearProcessRole(Object processObj, String rolename) throws WTException {
		// 获得对象的相关进程
		WfProcess process = getProcess(processObj);
		
		Team team = getTeam(process);
		
		clearTeamRole(team, rolename);
	}

	/**
	 * 清空流程团队中指定多个角色的参与者
	 * 
	 * @param processObj
	 *            工作流本身
	 * @param roles
	 *            指定角色列表
	 * @throws WTException
	 */
	public static void clearProcessRoles(Object processObj, Vector roles) throws WTException {
		// 获得对象的相关进程
		WfProcess process = getProcess(processObj);
		
		Team team = getTeam(process);
		
		for (int i = 0; i < roles.size(); i++) {
			String rolename = roles.elementAt(i).toString();
			
			clearTeamRole(team, rolename);
		}
	}

	/**
	 * 清空团队中指定角色的参与者
	 * 
	 * @param team
	 * @param rolename
	 * @throws WTException
	 */
	public static void clearTeamRole(Team team, String rolename) throws WTException {
		Enumeration enum1 = getRoleEnumeration(team, rolename);
		
		while (enum1 != null && enum1.hasMoreElements()) {
			WTPrincipal wtp = ((WTPrincipalReference) enum1.nextElement()).getPrincipal();
			System.out.println( "Debug clearTeamRole...wtp："+wtp.toString() );
			removePrincipalFromTeam(team, rolename, wtp);
		}
	}

	/**
	 * 获得对象的相关进程
	 * 
	 * @param obj
	 *            需要获取相关进程的对象，该对象可能为WfActivity、WorkItem等，也可能为WfProcess
	 * @return 相关进程 <br>
	 */
	public static WfProcess getProcess(Object obj) {
		if (obj == null) {
			return null;
		}

		try {
			Persistable persistable = null;

			if (obj instanceof ObjectIdentifier) {
				persistable = PersistenceHelper.manager.refresh((ObjectIdentifier) obj);
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    ObjectIdentifier ");
			} else if (obj instanceof ObjectReference) {
				persistable = ((ObjectReference) obj).getObject();
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    ObjectReference ");
			}
			if (obj instanceof Persistable) {
				persistable = (Persistable) obj;
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    Persistable ");
			}
			if (persistable instanceof WorkItem) {
				persistable = ((WorkItem) persistable).getSource().getObject();
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WorkItem ");
			}
			if (persistable instanceof WfActivity) {
				persistable = ((WfActivity) persistable).getParentProcess();
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfActivity ");
			}
			if (persistable instanceof WfConnector) {
				persistable = ((WfConnector) persistable).getParentProcessRef().getObject();
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfConnector ");
			}
			if (persistable instanceof WfBlock) {
				persistable = ((WfBlock) persistable).getParentProcess();
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfBlock ");
			}
			if (persistable instanceof WfProcess) {
				System.out.println("@@@@@@@@@@@@@@@@@@@@@@    WfProcess ");
				return (WfProcess) persistable;
			} else
				return null;
		} catch (Exception e) {
			if (VERBOSE) {
				System.out.println("WorkflowUtil.getProcess : error");
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 获取流程团队
	 * 
	 * @param process
	 *            流程实例
	 * @throws WTException
	 */
	public static Team getTeam(TeamManaged process) throws WTException {
		System.out.println("@@@@@@@@@@@@@@@@  start 获取流程团队 ");
		
		return TeamHelper.service.getTeam(process);
	}

	/**
	 * @param teammanaged
	 * @param rolename
	 * @return 团队角色中的用户集合
	 * @throws WTException
	 */
	public static Enumeration getRoleEnumeration(TeamManaged teammanaged,String rolename) throws WTException {
		Team team = getTeam(teammanaged);

		if (team == null) {
			return null;
		}

		return getRoleEnumeration(team, rolename);
	}

	/**
	 * 获取团队中指定角色的参与者
	 * 
	 * @param team
	 * @param rolename
	 * @return 团队角色中的用户集合
	 * @throws WTException
	 */
	public static Enumeration getRoleEnumeration(Team team,String rolename) throws WTException {
		Role role = Role.toRole(rolename);
		
		return team.getPrincipalTarget(role);
	}

	/**
	 * 从团队中的某个角色中移除指定的参与者
	 * 
	 * @param team
	 * @param rolename
	 * @param prin
	 * @return
	 */
	public static boolean removePrincipalFromTeam(Team team, String rolename,WTPrincipal prin) {
		if (prin instanceof WTUser) {
			boolean flag = true;

			try {
				Role role = Role.toRole(rolename) ;
				System.out.println( "Debug   removePrincipalFromTeam:"+role.getFullDisplay() );
				team.deletePrincipalTarget(role, prin);
			} catch (Exception e) {
				System.out.println("WorkflowUtil.deletePrincipalFromTeam : error");
				e.printStackTrace();
				flag = false;
			}

			return flag;
		} else if (prin instanceof WTGroup) {
			WTGroup group = (WTGroup) prin;
			try {
				Enumeration enumeration = group.members();
				while (enumeration.hasMoreElements()) {
					WTPrincipal principal = (WTPrincipal) enumeration.nextElement();
					boolean flag = removePrincipalFromTeam(team, rolename,principal);
					
					if (!flag) {
						return false;
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 为指定参与者赋予“修改”和“读取的权限”  add by kwang 2013-11-21
	 * @param wfSelf
	 * @param roleName
	 * @param list
	 */
	public static void setOrDelectAclForRole( ObjectReference wfSelf , String roleName , WTArrayList list ,boolean  opinion){
		System.out.println( "Debug   setOrDelectAclForRole(1)..." );
		if( opinion ){
			System.out.println( "Debug   开始运行赋予权限功能..." );
		}else{
			System.out.println( "Debug   开始运行删除权限功能..." );
		}
		if( wfSelf != null && roleName != null && list != null ){
			WfProcess process = getProcess( wfSelf );
			
			if( process == null ){
				System.out.println( "Debug   process NULL!" );
				return;
			}else{
				
				try {
					System.out.println( "开始动态设置流程中关联对象的权限" );
					setOrDelectAclForRole( process , roleName ,list ,opinion);
					System.out.println( "结束动态设置流程中关联对象的权限" );
				} catch (ObjectNoLongerExistsException e) {
					e.printStackTrace();
				} catch (WTException e) {
					e.printStackTrace();
				} catch (WTPropertyVetoException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 为指定参与者赋予“修改”和“读取的权限”
	 * @param process 流程对象	
	 * @param roleName 角色名称	
	 * @param list 赋予权限对象集合
	 * @param opinion 判断是赋予权限还是删除权限
	 * @throws ObjectNoLongerExistsException
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	private static void setOrDelectAclForRole(WfProcess process, String roleName, WTArrayList list ,boolean opinion) throws ObjectNoLongerExistsException, WTException, WTPropertyVetoException {
		System.out.println( "Debug   setOrDelectAclForRole(2)..." );
		// 获取流程 团队的特定角色的参与者
		System.out.println("开始获取团队角色") ;
		TeamManaged teamManaged = (TeamManaged) process ;
		TeamReference teamReference = (TeamReference) teamManaged.getTeamId();
		if( teamReference != null ){
			Team team = (Team) teamReference.getObject();
			
			if( team != null ){
				team = (Team) PersistenceHelper.manager.refresh(team);
			}	
			//根据名称获取指定角色
			Role role = Role.toRole( roleName );
			
			if( team != null && role != null ){
				//获取流程团队中的参与者
				System.out.println( "Debug   setOrDelectAclForRole - team："+team.getName() );
				Enumeration participants = team.getPrincipalTarget(role);
				
				if ((participants == null) || (!participants.hasMoreElements())){					
					System.out.println("Debug   参与者为空") ;					
					return;
				}
				
				while (participants.hasMoreElements()) {
					WTPrincipalReference principalRef = (WTPrincipalReference) participants.nextElement();
					
					if( principalRef != null ){
						Iterator iterator = list.persistableIterator();
						WTPrincipal principal = principalRef.getPrincipal();
						System.out.println( "Debug   获取到的用户或者组:"+principal.getName() );
						if( iterator != null ){
							
							while ( iterator.hasNext() ) {
								
								Persistable each = (Persistable)iterator.next();
								
								setOrDelectAclForRole( each , principal , opinion );
							}
						}
					}
					
				}
			}
		}
			
	}
	
	/**
	 * 为指定参与者赋予“修改”和“读取的权限”
	 * @param each  要设置权限的对象
	 * @param principal 要设置权限的用户/组
	 * @param opinion 判断是赋予权限还是删除权限
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	private static void setOrDelectAclForRole( Persistable each, WTPrincipal principal, boolean opinion ) throws WTPropertyVetoException, WTException {	
		System.out.println( "Debug   setOrDelectAclForRole(3)..." );
		boolean asBoolean = false ;
		if( each != null && principal != null ){
			Iterator< AccessPermission >  iterator = apList.iterator();
			
			if( iterator != null ){
				
				while ( iterator.hasNext() ) {
					AccessPermission accessPermission = iterator.next();
					//判断该用户/组对该对象是否有相应权限
					asBoolean = hasModifiedPrivilege( each ,principal,accessPermission );
					System.out.println( "Debug   asBoolean:"+asBoolean );
					if( opinion ){
						
						if( !asBoolean ){
							AccessUtil.setObjectAccess(each, principal , accessPermission);	
						}											
					}else{
						
						if( asBoolean ){
							AccessUtil.removeObjectAccess(each, principal, accessPermission);
						}				
					}				
				}
			}		
		}		
	}  
	
	/**
	 * 判断用户是否有相应权限
	 * @param persistable
	 * @param principal
	 * @param accessPermission
	 * @return
	 * @throws WTException
	 */
	private static boolean hasModifiedPrivilege( Persistable persistable , WTPrincipal principal ,AccessPermission accessPermission ) throws WTException {
		boolean hasModifiedPrivilege = false;

		if( principal != null && persistable != null && accessPermission != null ){
			//判断当前角色是否都当前对象有修改
			hasModifiedPrivilege = AccessControlHelper.manager.hasAccess(principal, persistable, accessPermission);		
		}
		return hasModifiedPrivilege;
	}
}
